﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Configuration;
using OAProject.Domain.Interfaces;
using OAProject.Domain.Entities;
using OAProject.Infrastructure.Data;

namespace OAProject.Infrastructure.Data
{
    public class UsersMenusRepository:DapperRepository<UsersMenus>, IUsersMenusRepository
    {
        //依赖注入
        public IConfiguration _configuration;

        public UsersMenusRepository(IConfiguration configuration)
        {
            this._configuration = configuration;
            //连接字符串
            this.ConnStr = _configuration.GetConnectionString("ConnStr");
            SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
            Conn = new MySql.Data.MySqlClient.MySqlConnection(this.ConnStr);
        }

        /// <summary>
        /// 实现接口查询树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<RoleMenus> RoleMenusShow(int id)
        {
            string sql = $"select c.MenuID,c.MenuName,c.ParentID,a.MenuID as MenuID1 from UsersMenus a join Users b on a.UserID=b.UserID right join Menus c on a.MenuID=c.MenuID and b.UserID={id}";
            return Conn.Query<RoleMenus>(sql).ToList();
        }

        /// <summary>
        /// 修改用户权限
        /// </summary>
        /// <param name="menuIds"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public int AddRoleMenus(List<int> menuIds, int userId)
        {
           
            //开启事务(数据一致性的保证)
            Conn.Open();
            using (var tran = Conn.BeginTransaction())
            {
                try
                {
                    int result = 0;
                    //清空roleId这个角色在RoleMenus表的所有权限(Delete语句)
                    string sqlDelete = "delete from UsersMenus where UserId=@p1";//参数化
                    result = Conn.Execute(sqlDelete, new { p1 = userId }, tran);

                    //批量添加把menuids全部加入到RoleMens表里
                    string sqlInsert = "insert into UsersMenus values(@MenuID,@UserId)";

                    foreach (int item in menuIds)
                    {
                        result += Conn.Execute(sqlInsert, new {  MenuID = item, UserId = userId }, tran);
                    }

                    //成功,commit提交事务
                    tran.Commit();
                    return result;

                }
                catch (Exception)
                {
                    //失败,rollback
                    tran.Rollback();
                    return -1;
                }
            }
        }
    }
}
